package com.qcby.shiwu;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class TransactionProxy implements InvocationHandler {
    private final Object target;
    private final TransactionManager transactionManager;

    public TransactionProxy(Object target, TransactionManager transactionManager) {
        this.target = target;
        this.transactionManager = transactionManager;
    }

    public static Object createProxy(Object target, TransactionManager transactionManager) {
        return Proxy.newProxyInstance(
                target.getClass().getClassLoader(),
                target.getClass().getInterfaces(),
                new TransactionProxy(target, transactionManager)
        );
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        if (method.isAnnotationPresent(Transactional.class)) {
            try {
                transactionManager.beginTransaction();
                Object result = method.invoke(target, args);
                transactionManager.commit();
                return result;
            } catch (Exception e) {
                transactionManager.rollback();
                throw e;
            }
        }
        return method.invoke(target, args);
    }
}
